package com.woniu.aimd.config.ai.chatclient.chatMemory;




import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniu.aimd.pojo.entity.Msg;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.ai.chat.messages.Message;
import java.util.ArrayList;
import java.util.List;
@Component
public class RedisChatMemory  implements ChatMemory {
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public void add(String conversationId, List<Message> messages) {


        List<String> chatHistory = messages.stream().map(Msg::new).map(msg->{
            try {
                System.out.println(msg);
                return objectMapper.writeValueAsString(msg);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }).toList();
        //push会话历史到redis中
        redisTemplate.opsForList().rightPushAll(conversationId,chatHistory);


    }

    @Override
    public List<Message> get(String conversationId) {
        List<String> redisArray = redisTemplate.opsForList().range(conversationId,0, -1);
        if (redisArray.isEmpty()){
            return List.of();
        }
        //转换成集合
        return  redisArray.stream().map(message -> {
            try {
                System.out.println(message);
                return objectMapper.readValue(message, Msg.class);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }).map(Msg::toMessage).toList();
    }

    @Override
    public void clear(String conversationId) {
        redisTemplate.delete(conversationId);
    }
}
